/* Copyright  2009
   @Author
   Richard Changde Yin            e-mail yinchangde@hotmail.com

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include <server_includes.h>
#include CSTDINT_H
#include <function/math/rand.h>
/// For util_randominit.
#include <util.h>
#include <session.h>

void Item_func_rand::seed_random(Item *arg)
{
  /*
    TODO: do not do reinit 'rand' for every execute of PS/SP if
    args[0] is a constant.
  */
  uint64_t tmp= (uint64_t) arg->val_int();
  util_randominit(rand, (tmp*0x10001L+55555555L),
                           (tmp*0x10000001L));
}

bool Item_func_rand::fix_fields(Session *session,Item **ref)
{
  if (Item_real_func::fix_fields(session, ref))
    return true;
  used_tables_cache|= RAND_TABLE_BIT;
  if (arg_count)
  {                                     // Only use argument once in query
    /*
      No need to send a Rand log event if seed was given eg: RAND(seed),
      as it will be replicated in the query as such.
    */
    if (!rand && !(rand= (struct rand_struct*)
                   session->alloc(sizeof(*rand))))
      return true;

    if (args[0]->const_item())
      seed_random (args[0]);
  }
  else
  {
    rand= &session->rand;
  }
  return false;
}

void Item_func_rand::update_used_tables()
{
  Item_real_func::update_used_tables();
  used_tables_cache|= RAND_TABLE_BIT;
}

static double util_my_rnd(struct rand_struct *rand_st)
{
  rand_st->seed1=(rand_st->seed1*3+rand_st->seed2) % rand_st->max_value;
  rand_st->seed2=(rand_st->seed1+rand_st->seed2+33) % rand_st->max_value;
  return (((double) rand_st->seed1)/rand_st->max_value_dbl);
}

double Item_func_rand::val_real()
{
  assert(fixed == 1);
  if (arg_count && !args[0]->const_item())
    seed_random (args[0]);
  return util_my_rnd(rand);
}

